package com.leyou.item.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPageAndSort(
            Integer page,Integer rows,String sortBy,Boolean desc ,String key
    ){


        //开始分页
        PageHelper.startPage(page,rows);
        //过滤
        Example example = new Example(Brand.class);
        if(StringUtils.isNotBlank(key)){
            example.createCriteria().andLike("name","%"+key+"%").orEqualTo("letter",key);
        }
        if(StringUtils.isNotBlank(sortBy)){
            //排序
            String orderRule = sortBy +" "+ (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderRule);
        }
        Page<Brand> brands = (Page<Brand>)brandMapper.selectByExample(example);
        //封装数据
        PageResult<Brand> result = new PageResult<>(brands.getTotal(),brands);
        //放回结果
        return result;

    }

    @Transactional
    public void saveBrand(Brand brand,List<Long>cids){

        this.brandMapper.insertSelective(brand);
        for(Long l : cids){
            this.brandMapper.insertCategoryBrand(l,brand.getId());
        }
    }
    @Transactional
    public void updateBrand(Brand brand,List<Long> cids){
            this.brandMapper.updateByPrimaryKeySelective(brand);
            this.brandMapper.deleteCategoryBrandByBid(brand.getId());
            for(Long l : cids){
                this.brandMapper.insertCategoryBrand(l,brand.getId());
            }
    }

    @Transactional
    public void deleteBrandById(Long id){
        brandMapper.deleteCategoryBrandByBid(id);
        brandMapper.deleteByPrimaryKey(id);
    }

    public List<Brand> queryBrandByCid(Long cid){
       /* Brand brand = new Brand();
        List<Long> longs = this.brandMapper.selectBrandIdByCid(cid);
        ArrayList<Brand> brands = new ArrayList<>();
        longs.forEach(l -> {
            Brand brand1 = this.brandMapper.selectByPrimaryKey(l);
            brands.add(brand1);
        });
        return brands;*/
        List<Brand> brands = this.brandMapper.queryBrandsByCid(cid);
        return brands;
    }

    public Brand queryBrandByBid(Long bid){
        Brand brand = this.brandMapper.selectByPrimaryKey(bid);
        return brand;
    }

    public List<Brand> queryBrandsByIds(List<Long> ids){
        List<Brand> brands = this.brandMapper.selectByIdList(ids);
        return brands;
    }

}
